package com.qf.smsplatform.monitor.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.RabbitMQConstants;
import com.qf.smsplatform.monitor.service.api.CacheService;
import com.qf.smsplatform.monitor.util.JavaMailUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Set;

@Component
@Slf4j
public class MonitorRabbitJob implements SimpleJob {

    @Autowired
    private CacheService cacheService;

    //2. 获取Channel对象
    @Autowired
    private Channel channel;

    @Autowired
    private JavaMailUtil javaMailUtil;

    @Override
    public void execute(ShardingContext shardingContext)  {
        //1. 调用cacheService查询当前所有通道的id，获取到所以的队列名
        Set<String> keys = cacheService.keys(CacheConstants.CACHE_PREFIX_SMS_CHANNEL + "*");
        for (String key : keys) {
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + key.substring(key.lastIndexOf(":") + 1);

            try {
                channel.queueDeclare(queueName,true,false,false,null);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //3. 通过Channel对象的API监听当前队列中的消息.
            AMQP.Queue.DeclareOk declareOk = null;
            try {
                declareOk = channel.queueDeclarePassive(queueName);
            } catch (IOException e) {
                e.printStackTrace();
            }

            int count = declareOk.getMessageCount();

            if(count >= 100) {
                //4. 如果消息超过1个,发送邮件给运维人员.
                try {
                    log.info("【监听模块】 {}队列出现消息堆积情况，共{}条",queueName,count);
                    javaMailUtil.sendMail(count);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    System.out.println("发送邮件失败!!!!!!!!!");
                }
            }
            log.info("【监听模块】 {}队列没有出现消息堆积情况",queueName);
        }
    }
}
